import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;


import java.io.FileOutputStream;

public class PdfUtil {

    /**
     * 合并两个pdf文件
     * "E:/pdf/1.pdf"  "E:/pdf/2.pdf" : 需要合并的pdf文件 可以多个
     * "E:/pdf/3.pdf" 合并后的文件
     * @param args
     */
    public static void main(String[] args) {
        String path1 = "C:\\Users\\EDZ\\Desktop\\汇添富出差20231121-20231124\\";
//        String path2 = "C:\\Users\\EDZ\\Desktop\\汇添富出差202300522-20230526\\餐饮\\";

        int sum = 2;
        String[] files1 = new String[sum];
        for(int i = 0;i < sum;i++){
            String path = path1 + (i+1)+".pdf";
            files1[i] = path;
        }
//        System.out.println(files1);

        String savePath1 = path1+"../合并.pdf";
        mergePdfFiles(files1, savePath1);

//        String[] files2 = { path1+"【曹操出行-39.66元-1个行程】高德打车电子行程单.pdf",
//                path1+"【高德打车-30.30元-1个行程】高德打车电子行程单.pdf",
//                path1+"【享道出行-39.34元-1个行程】高德打车电子行程单.pdf"
//        };
//        String savePath2 = path1+"/result2.pdf";
//        mergePdfFiles(files2, savePath2);
    }

    //合并方法
    public static boolean mergePdfFiles(String[] files, String newFile) {
        boolean retValue = false;
        Document document = null;
        try {
            document = new Document(new PdfReader(files[0]).getPageSize(1));
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(newFile));
            document.open();
            for (int i = 0; i < files.length; i++) {
                PdfReader reader = new PdfReader(files[i]);
                int n = reader.getNumberOfPages();
                for (int j = 1; j <= n; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);
                    copy.addPage(page);
                }
            }
            retValue = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
        return retValue;
    }

}
